#include <stdlib.h>
#include "N1Lib.h"
#include "N2Lib.h"

#define UDP_PORT  12445

void N1SocketUDPTestThread2(void*)
{
    N1AutoreleasePool pool;

    N1Socket *s = N1Socket::udpSocket();
    char buff[100];
    N1NetworkAddress *addr = NULL;
    uint32 size;

    s->bind(NULL, UDP_PORT);

    //s->setBlockMode(true);

    while(1)
    {
        size = s->recvfrom(buff, sizeof(buff), &addr);

#ifdef WINDOWS
        if (size==ULONG_MAX) printf("WSA=%u\n", WSAGetLastError());
#else
        if (size==ULONG_MAX) printf("WSA=%u\n", errno);
#endif

        //N1CHECK(size, "Error in recvfrom");

        if(strcmp(buff, "end")==0) break;

        uint32 var = atoi(buff);

        printf("%s %d %x\n", buff, var, size);

        strcpy(buff, "Hi, great programmer!!!!!");
 
        s->sendto(buff, strlen(buff)+1, addr);
    }
}  

void N1SocketUDPPerformance()
{
    N1AutoreleasePool pool;

    N1Socket *s = N1Socket::udpSocket();

    N1Thread::detachNewThread(N1SocketUDPTestThread2, NULL);

    N1Thread::sleep(1000);

    char buff[100];
    N1NetworkAddress *addr = new N1NetworkAddressIPv4("127.0.0.1", UDP_PORT);
    addr->autorelease();
    uint32 size;

    for(uint32 i=0;i<10000;i++)
    {
       sprintf(buff, "%u", i);
 
       s->sendto(buff, strlen(buff)+1, addr);

       size = s->recvfrom(buff, sizeof(buff), &addr);

    }
    sprintf(buff, "end");
 
    s->sendto(buff, strlen(buff)+1, addr);
}


int main(int argc, const char** argv)
{
    N1LibInitialize();
    N2LibInitialize();

    //N1UNIT_RUN_TESTS;
    //N1UNIT_RUN_TESTS_BY_MASK(N2);

    N2Window w(100,100);

    N2Window::runLoop(1);

    //N1SocketUDPPerformance();

    //*(char*)NULL = 0;

    return 0;
}
